package com.example.sunmiv1.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.view.View;
import android.view.WindowManager;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sunmiv1.R;
import com.example.sunmiv1.adapter.CollectRecordAdapter;
import com.example.sunmiv1.entity.CollectRecordInfo;
import com.example.sunmiv1.utils.Tools;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.GsonUtils;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.LoadingDialog;
import com.example.sunmiv1.utils.net.TextCallBack;
import com.example.sunmiv1.utils.zxing.Constant;
import com.example.sunmiv1.utils.zxing.activity.CaptureActivity;
import com.example.sunmiv1.vm.CollectRecordViewModel;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.luck.picture.lib.listener.OnItemClickListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import kotlinx.coroutines.GlobalScope;


// 快速收款.快速收款列表
public class CollectRecordActivity extends Activity {
    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_title)
    TextView titleTitle;
    @BindView(R.id.tv_start_time)
    TextView tvStartTime;
    @BindView(R.id.tv_end_time)
    TextView tvEndTime;
    
    @BindView(R.id.edit_collectRecord)
    EditText editCollectRecord;
    @BindView(R.id.scan_collectRecord)
    ImageView scanCollectRecord;
    @BindView(R.id.search_collectRecord)
    ImageView searchCollectRecord;
    @BindView(R.id.listView_collectRecord)
    PullToRefreshListView listViewCollectRecord;
    @BindView(R.id.btn_to_top)
    ImageView btnToTop;
    @BindView(R.id.scan_view)
    LinearLayout mScanView;

    private ACache aCache;
    private int page = 1;
    private Context context;
    private LoadingDialog loadingDialog;

    private CollectRecordInfo collectRecordInfo;
    private List<CollectRecordInfo.DataBean> list = new ArrayList<>();

    private CollectRecordAdapter collectRecordAdapter;
    private CollectRecordViewModel mViewModel;

    public static final String REFUND_KEY="isRefund";
    private boolean mHashRefund=false;

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    for (CollectRecordInfo.DataBean dataBean : collectRecordInfo.getData()) {
                        list.add(dataBean);
                    }
                    page++;
                    setCollectRecordAdapter();
                    break;
                case 2:
                    setCollectRecordAdapter();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_collect_record);
        mHashRefund=getIntent().getBooleanExtra(REFUND_KEY,false);
        ButterKnife.bind(this);
        titleTitle.setText(R.string.collectRecordTitle);
        mViewModel=new CollectRecordViewModel(this);
        context = this;
        aCache = ACache.get(context);
        loadingDialog = new LoadingDialog(context);
        initListener();
        getRecord();
        mScanView.setVisibility(mHashRefund?View.GONE:View.VISIBLE);
    }

    private void initListener() {
        listViewCollectRecord.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                page = 1;
                list.clear();
                setCollectRecordAdapter();
                getRecord();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                getRecord();
            }
        });
    }


    @OnClick({R.id.title_back, R.id.tv_start_time,R.id.btn_to_top, R.id.tv_end_time, R.id.scan_collectRecord, R.id.search_collectRecord})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.tv_start_time:
                getDateFromDatePickerDialog(tvStartTime);
                break;
            case R.id.tv_end_time:
                getDateFromDatePickerDialog(tvEndTime);
                break;
            case R.id.scan_collectRecord:
                startQrCode();
                break;
            case R.id.search_collectRecord:
                page = 1;
                list.clear();
                setCollectRecordAdapter();
                getRecord();
                break;
            case R.id.btn_to_top:
                listViewCollectRecord.getRefreshableView().setSelection(0);
                break;
        }
    }

    private void setCollectRecordAdapter() {
        if (collectRecordAdapter == null) {
            collectRecordAdapter = new CollectRecordAdapter(context, list);
            listViewCollectRecord.setAdapter(collectRecordAdapter);
            collectRecordAdapter.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(View v, int position) {
                    if(mHashRefund){
                        Intent data=new Intent();
                        data.putExtra("data",list.get(position).getOut_trade_no());
                        setResult(CollectRecordActivity.RESULT_OK,data);
                        finish();
                    }
                }
            });
            mViewModel.init(collectRecordAdapter);
        } else {
            collectRecordAdapter.notifyDataSetChanged();
        }
    }

    //
    private void getRecord() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("cashier_id", aCache.getAsString("uid"));
            jsonObject.put("start_time", tvStartTime.getText().toString().trim());
            jsonObject.put("end_time", tvEndTime.getText().toString().trim());
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            if ("1".equals(aCache.getAsString("userType")) || "2".equals(aCache.getAsString("userType"))) {
                jsonObject.put("operator_id", aCache.getAsString("operator_id"));
            } else {
                jsonObject.put("operator_id", aCache.getAsString("uid"));
            }
            jsonObject.put("user_type", aCache.getAsString("userType"));
            jsonObject.put("out_trade_no", editCollectRecord.getText().toString().trim());
            jsonObject.put("page", page);
            jsonObject.put("limit", 20);
            jsonObject = Tools.createParameterCode(jsonObject);
            HttpUtils.post(context, Common.QUICK_LIST, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    listViewCollectRecord.onRefreshComplete();
                    collectRecordInfo = GsonUtils.JsonToBean(text, CollectRecordInfo.class);
                    Message msg = new Message();
                    if (collectRecordInfo.getStatus() == 1) {
                        msg.what = 1;
                    } else {
                        msg.what = 2;
                    }
                    handler.sendMessage(msg);
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                    listViewCollectRecord.onRefreshComplete();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    // 開始掃碼
    private void startQrCode() {
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 申請權限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, Constant.REQ_PERM_CAMERA);
            return;
        }
        // 二維碼掃碼
        Intent intent = new Intent(context, CaptureActivity.class);
        startActivityForResult(intent, Constant.REQ_QR_CODE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constant.REQ_PERM_CAMERA:
                // 攝像頭權限申請
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 獲得授權
                    startQrCode();
                } else {
                    // 被禁止授權
                    Toast.makeText(context, "請至權限中心打開本應用的相機訪問權限", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode != 1 && requestCode == Constant.REQ_QR_CODE && resultCode == RESULT_OK) {//掃描結果回調
            Bundle bundle = data.getExtras();
            page = 1;
            list.clear();
            setCollectRecordAdapter();
            editCollectRecord.setText(bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN));
            getRecord();
        }
    }
    /**
     * 點擊某個textView，調起時間選擇器，設置該時間選擇器返回的時間給該textView
     * @param tv textView
     */
    private void getDateFromDatePickerDialog(TextView tv){
        Calendar calendar = Calendar.getInstance();
        new DatePickerDialog(this, AlertDialog.THEME_HOLO_LIGHT, new DatePickerDialog.OnDateSetListener() {
            // 綁定監聽器(How the parent is notified that the date is set.)
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                // 此處得到選擇的時間，可以進行你想要的操作
                if ((monthOfYear + 1) < 10) {
                    tv.setText(year + "-0" + (monthOfYear + 1) + "-" + dayOfMonth);
                } else {
                    tv.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
                }
            }
        }// 設置初始日期
                , calendar.get(Calendar.YEAR)
                , calendar.get(Calendar.MONTH)
                , calendar.get(Calendar.DAY_OF_MONTH)).show();
    }
}
